import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import streamlit as st
# 以画数据图表的方式展示数据
file = r"outputs\city\china_cities_20210111.csv"
plt.rcParams['font.sans-serif'] = 'SimHei'

st.set_option('deprecation.showPyplotGlobalUse', False)


# 返回所有城市的数据，全部城市的名字， 随机选取的数
def get_random_city(file):
    data = pd.read_csv(file)


    city_name_list = data.columns
    # 随机一个城市，6种污染物，24h内的浓度折线图在一个图上展示 (n+15)
    # 随机选取一个城市所在列
    random_city_code = np.random.randint(4, data.shape[1])
    data = data.iloc[:, random_city_code]

    return {"data": data, "city_name_list": city_name_list, "random_city_code": random_city_code}


def draw_line(data, city_name_list, random_city_code):
    PM2_5 = []
    for i in range(1, data.shape[0], 15):
        PM2_5.append(data.iloc[i])

    PM10 = []
    for i in range(3, data.shape[0], 15):
        PM10.append(data.iloc[i])
    SO2 = []
    for i in range(5, data.shape[0], 15):
        SO2.append(data.iloc[i])

    NO2 = []
    for i in range(7, data.shape[0], 15):
        NO2.append(data.iloc[i])
    O3 = []
    for i in range(9, data.shape[0], 15):
        O3.append(data.iloc[i])

    CO = []
    for i in range(13, data.shape[0], 15):
        CO.append(data.iloc[i])

    x = [a for a in range(1, 25)]
    plt.subplot(2, 1, 1)
    plt.plot(x, PM2_5, label='PM2_5')
    # 绘制第二条折线
    plt.plot(x, PM10, label='PM10')
    plt.plot(x, SO2, label='SO2')
    plt.plot(x, NO2, label='NO2')
    plt.plot(x, O3, label='O3')
    plt.plot(x, CO, label='CO')

    # 设置图表标题和轴标签
    plt.title(f"{city_name_list[random_city_code]}")
    plt.xlabel("时间")
    plt.ylabel("浓度")

    # 添加图例
    plt.legend(loc="best")

    # 显示图表
    st.pyplot()


def draw_bar(data, city_name_list, random_city_code):
    nd = []

    # 获取随机时间(n*14 + 14)
    # 1--14 16--29 31--44
    random_time = np.random.randint(0, 24)
    a = [i for i in range(0, data.shape[0], 15)]
    data = data.iloc[a[random_time]:a[random_time] + 15]
    for i in range(1, 15, 2):
        nd.append(data.iloc[i])
    x = ["PM2.5", "PM10", "SO2", "NO2", "O3",  "CO"]
    del nd[-2]
    plt.subplot(2, 1, 2)
    plt.title(f"{city_name_list[random_city_code]}")
    plt.xlabel("污染物种类")
    plt.ylabel("浓度")
    plt.bar(x, nd)
    st.pyplot()


draw_line(**get_random_city(file))
draw_bar(**get_random_city(file))
